package com.samnative.pineapple.main;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.blankj.utilcode.util.LogUtils;
import com.samnative.pineapple.adapter.MyFragmentAdapter;
import com.samnative.pineapple.entity.MessageEvent;
import com.samnative.pineapple.entity.UpdataModel;
import com.samnative.pineapple.fragment.MainHomeFragment;
import com.samnative.pineapple.fragment.MainMineFragment;
import com.samnative.pineapple.fragment.HomeSearchFragment;
import com.samnative.pineapple.http.HttpRequest;
import com.samnative.pineapple.http.JsonResult;
import com.samnative.pineapple.instance.AppPrefer;
import com.samnative.pineapple.service.MainService;
import com.samnative.pineapple.utils.GsonUtils;
import com.samnative.pineapple.utils.NoticePermissUtil;
import com.samnative.pineapple.utils.PackageUtils;
import com.samnative.pineapple.value.Config;
import com.samnative.pineapple.widget.UpdataDialog;
import com.samnative.pineapple.widget.WenxinDialog;
import com.gyf.immersionbar.ImmersionBar;
import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.v3.MessageDialog;
import com.shashank.sony.fancytoastlib.FancyToast;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;


/**
 * 主页面
 */
public class MainActivity extends BaseActivity implements OnClickListener, EasyPermissions.PermissionCallbacks {


    /**
     * ViewPager控件
     */
    private ViewPager mViewPager;
    /**
     * RadioGroup控件
     */
    private RadioGroup mRadioGroup;
    /**
     * rb按钮
     */
    private RadioButton rb1, rb2, rb5;
    /**
     * 碎片视图列表
     */
    private List<Fragment> mFragments;
    /**
     * 首页
     */
    private MainHomeFragment mainHomeFragment;
    /**
     * 搜索
     */
    private HomeSearchFragment zixunFragment;
    /**
     * 我的
     */
    private MainMineFragment mainMineFragment;
    /**
     * 分布适配器
     */
    private MyFragmentAdapter mfrFragmentAdapter;
    /**
     * 记录当前选中的tab下标
     */
    private int index = 0;
    /**
     * 更新提示框
     */
    private UpdataDialog updataDialog;
    /**
     * 更新的model
     */
    private UpdataModel upModel;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        ImmersionBar.with(this).statusBarDarkFont(true).init();
        swipePanel.setLeftEnabled(false);
        mViewPager = find(R.id.main_viewpager);
        mainHomeFragment = new MainHomeFragment();
        zixunFragment = new HomeSearchFragment();
        mainMineFragment = new MainMineFragment();
        mFragments = new ArrayList<>();
        mFragments.add(mainHomeFragment);
        mFragments.add(zixunFragment);
        mFragments.add(mainMineFragment);
        mfrFragmentAdapter = new MyFragmentAdapter(getSupportFragmentManager(),
                mFragments);
        mViewPager.setAdapter(mfrFragmentAdapter);

        mRadioGroup = find(R.id.main_radiogroup);
        rb1 = find(R.id.main_radiobutton_1);
        rb2 = find(R.id.main_radiobutton_2);
        rb5 = find(R.id.main_radiobutton_5);
        mRadioGroup.setOnCheckedChangeListener(mOnCheckedChangeListener);
        mRadioGroup.check(R.id.main_radiobutton_1);
//
//        requestHttpUpdata();
        if (!AppPrefer.getInstance(mContext).getBoolean(AppPrefer.isPrivacyPolicy, false)) {
            //弹出隐私协议，提示
            WenxinDialog.getInstance(mContext, new WenxinDialog.Click() {
                @Override
                public void ok() {
                    AppPrefer.getInstance(mContext).put(AppPrefer.isPrivacyPolicy, true);
                    yinsiInit();
                }

                @Override
                public void cancel() {
                    finish();
                }
            }).show();
        } else {
            yinsiInit();
        }

    }


    /**
     * 同意了隐私协议
     */
    public void yinsiInit() {
        if (!NoticePermissUtil.areNotificationsEnabled(mContext)) {
            NoticePermissUtil.gotoNotificationSetting(this);
        }
        getH5Open(getIntent());
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        String token = AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, "");
        boolean isPrivacyPolicy = AppPrefer.getInstance(mContext).getBoolean(AppPrefer.isPrivacyPolicy, false);
        if (!token.equals("") && !UMConfigure.isInit && isPrivacyPolicy) {
            Log.e("2255", "用户已经注册/登录,且没有初始化友盟,此时可以真正初始化友盟SDK");
            //友盟分享初始化
            UMConfigure.init(this, Config.umengKey, "umeng", UMConfigure.DEVICE_TYPE_PHONE, "");
            PlatformConfig.setWeixin(Config.wechatId, Config.wechatKey);
            PlatformConfig.setWXFileProvider(getPackageName() + ".FileProvider");
            PlatformConfig.setQQZone(Config.qqId, Config.qqKey);
            PlatformConfig.setQQFileProvider(getPackageName() + ".FileProvider");
            PlatformConfig.setSinaWeibo(Config.sinaId, Config.sinaKey, "http://sns.whalecloud.com");
            PlatformConfig.setSinaFileProvider(getPackageName() + ".FileProvider");
        }
    }


    /**
     * 判断是否从H5上打开本应用
     *
     * @param intent
     */
    public void getH5Open(Intent intent) {
        Uri uri = intent.getData();
        if (uri != null) {
            String url = uri.toString();
            if (!url.contains("fzt://fzt.com")) {
                return;
            }
            Log.e("2255", "H5启动app的参数=" + url);
            String scheme = uri.getScheme();
            String host = uri.getHost();
            int port = uri.getPort();
            String path = uri.getPath();
            List<String> pathSegments = uri.getPathSegments();
            String query = uri.getQuery();

        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    /**
     * 单选点击监听
     */
    OnCheckedChangeListener mOnCheckedChangeListener = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // TODO Auto-generated method stub
            switch (checkedId) {
                case R.id.main_radiobutton_1:
                    index = 0;
                    mViewPager.setCurrentItem(index, false);
                    setCheched(index);
                    ImmersionBar.with(MainActivity.this).statusBarDarkFont(true).init();
                    break;
                case R.id.main_radiobutton_2:
                    index = 1;
                    mViewPager.setCurrentItem(index, false);
                    setCheched(index);
                    ImmersionBar.with(MainActivity.this).statusBarDarkFont(true).init();
                    break;
                case R.id.main_radiobutton_5:
//                    if (AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, "").equals("")) {
//                        Intent intent = new Intent(mContext, LoginActivity.class);
//                        startActivityForResult(intent, 200);
//                        mViewPager.setCurrentItem(index, false);
//                        setCheched(index);
//                        return;
//                    } else {
                    index = 2;
                    mViewPager.setCurrentItem(index, false);
                    setCheched(index);
//                    }
                    ImmersionBar.with(MainActivity.this).statusBarDarkFont(true).init();
                    break;
                default:
                    break;
            }
        }

    };

    //设置底部tab选中
    private void setCheched(int index) {
        switch (index) {
            case 0:
                rb1.setChecked(true);
                break;
            case 1:
                rb2.setChecked(true);
                break;
            case 2:
                rb5.setChecked(true);
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            default:
                break;
        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        super.onNewIntent(intent);
        boolean home = intent.getBooleanExtra("home", false);
        if (home) {
            LogUtils.e("选中主页");
            index = 0;
            mViewPager.setCurrentItem(index, false);
            setCheched(index);
            if (mainHomeFragment.getTitleAlpha() > 0.1f) {
                ImmersionBar.with(this).statusBarDarkFont(true).init();
            } else {
                ImmersionBar.with(this).statusBarDarkFont(true).init();
            }
        }

        boolean relogin = intent.getBooleanExtra("relogin", false);
        if (relogin) {
            Log.e("2255", "用户切换了账号");
        }

        getH5Open(intent);
    }


    /**
     * 检测版本更新
     */
    private void requestHttpUpdata() {
        // TODO Auto-generated method stub
        Map<String, String> map = new HashMap<String, String>();
        map.put("_apiname", "sys.index.versionupdate");
        map.put("version", "" + PackageUtils.getAppVersionCode(mContext));
        HttpRequest.post(this, null,
                map, new JsonResult() {
                    @Override
                    public void reqestSuccess(JSONObject result) {
                        if (MainActivity.this.isFinishing()) {
                            return;
                        }
                        try {
                            JSONObject jsonData = result.getJSONObject("data");
                            upModel = GsonUtils.fromJson(jsonData.toString(),
                                    UpdataModel.class);

//                            upModel.setUpdate("2");
//                            upModel.setUrl("http://a7.pc6.com/lyx6/huobiOTC.apk");

                            if (upModel.getUpdate().equals("") || upModel.getUpdate().equals("0")) {
                                return;
                            }

                            updataDialog = new UpdataDialog(mContext, upModel, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (v.getId() == R.id.tv_ok) {
                                        if (EasyPermissions.hasPermissions(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                            isDownload(upModel, Environment.getExternalStorageDirectory() + "/" +
                                                    mContext.getPackageName() + ".apk");
                                        } else {
                                            EasyPermissions.requestPermissions(MainActivity.this, "\"" + getString(R.string.app_name) + "\"更新版本需要获取储存权限,请确认",
                                                    100, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                                        }
                                    } else {
                                        updataDialog.cancel();
                                    }
                                }
                            });
                            updataDialog.show();

                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void requestFailure(int code, String msg) {
                        super.requestFailure(code, msg);
                    }
                });
    }

    /**
     * 是否已经下载了更新安装包
     * <p>
     * 如果新版安装包之前已经下好了，就直接打开安装
     * 没有没下载，立即去下载，下完了打开安装
     *
     * @param filePath 本地路径
     * @param upModel  下载地址等
     */
    public void isDownload(UpdataModel upModel, String filePath) {

        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            FancyToast.showToast(mContext, getString(R.string.no_sdcard), FancyToast.ERROR, false);
            return;
        }

        if (PackageUtils.getApkVisonCode(mContext, filePath) > PackageUtils.getAppVersionCode(mContext)) {
            setInstallPermission();
        } else {
            if (upModel.getUpdate().equals("1")) {
                // 非强制更新
                updataDialog.cancel();
            }
            Intent intent = new Intent(mContext, MainService.class);
            intent.putExtra(Config.SERVICE_KEY,
                    Config.SERVICE_DOWNLOAD_UPDATA);
            intent.putExtra("downloadurl", upModel.getUrl());
            intent.putExtra("versionName", upModel.getNew_version());
            startService(intent);
        }

    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        //强制更新的情况下,dialog实时接收下载进度
        if (updataDialog != null && updataDialog.isShowing()) {
            //下载进度显示
            if (event.getDownLoadPro() >= 0) {
                updataDialog.setProgressBar(event.getDownLoadPro());
            }
            //下载完成显示
            if (event.isDownLoadEnd()) {
                updataDialog.setDownLoadEnd();
            }
        }

        //下载完成的情况下
        if (event.isDownLoadEnd()) {
            setInstallPermission();
        }

        //其它文件下载完成的情况
        if (event.isOtherDownloadEnd()) {
            FancyToast.showToast(mContext, "文件下载完成,保存位置为" +
                    Environment.getExternalStorageDirectory().getAbsolutePath() + "/FZT/", FancyToast.SUCCESS, true);

        }
    }


    /**
     * 更新下载完APK后,判断这个
     * <p>
     * 8.0以上系统设置安装未知来源权限
     * <p>
     * 8.0以下直接打开安装
     */
    public void setInstallPermission() {

        //API大于26,作以下处理
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //先判断是否有安装未知来源应用的权限
            boolean haveInstallPermission = getPackageManager().canRequestPackageInstalls();
            if (!haveInstallPermission) {
                //没有未知来源权限,弹框提示用户手动打开
                MessageDialog.show(MainActivity.this, "安装权限", "需要打开允许来自此来源，请去设置中开启此权限", "确定", "取消").setOnOkButtonClickListener(
                        new OnDialogButtonClickListener() {
                            @Override
                            public boolean onClick(BaseDialog baseDialog, View v) {
                                //此方法需要API>=26才能使用
                                toInstallPermissionSettingIntent();
                                return false;
                            }
                        });
            } else {
                //已经有了未知来源权限,直接安装
                PackageUtils.installNormal(mContext, Environment.getExternalStorageDirectory() + "/" +
                        mContext.getPackageName() + ".apk");
            }
        } else {
            //低于26的不需要这个操作,直接安装
            PackageUtils.installNormal(mContext, Environment.getExternalStorageDirectory() + "/" +
                    mContext.getPackageName() + ".apk");
        }
    }

    public static final int INSTALL_PERMISS_CODE = 20001;

    /**
     * 开启安装未知来源权限
     */
    private void toInstallPermissionSettingIntent() {
        Uri packageURI = Uri.parse("package:" + getPackageName());
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        startActivityForResult(intent, INSTALL_PERMISS_CODE);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == INSTALL_PERMISS_CODE) {
            //用户打开了未知来源,可以安装
            PackageUtils.installNormal(mContext, Environment.getExternalStorageDirectory() + "/" +
                    mContext.getPackageName() + ".apk");
        }
    }


    @Override
    public void onBackPressed() {
        exitApp();
    }

    /**
     * 记录返回键按下时间
     */
    private long exitTime = 0;

    /**
     * 返回键双击退出APP
     */
    public void exitApp() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            FancyToast.showToast(mContext, getString(R.string.agintouch_exit), FancyToast.DEFAULT, false);
            exitTime = System.currentTimeMillis();
        } else {
            finish();
//            Intent intent = new Intent();// 创建Intent对象
//            intent.setAction(Intent.ACTION_MAIN);// 设置Intent动作
//            intent.addCategory(Intent.CATEGORY_HOME);// 设置Intent种类
//            startActivity(intent);// 将Intent传递给Activity
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

        //requestCode=100为点击更新请求的写入权限,用户许可后开始更新
        if (requestCode == 100) {
            isDownload(upModel, Environment.getExternalStorageDirectory() + "/" +
                    mContext.getPackageName() + ".apk");
        }

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        /**
         * 若是在权限弹窗中，用户勾选了'NEVER ASK AGAIN.'或者'不在提示'，且拒绝权限。
         * 这时候，需要跳转到设置界面去，让用户手动开启。
         */
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this)
                    .setTitle("权限请求")
                    .setRationale(getString(R.string.app_name) + "需要获取相关权限才能正常使用").setThemeResId(android.R.style.Theme_Holo_Dialog)
                    .build().show();
        }
    }


}
